(ns utilities.servidor 
(:gen-class))
(use 'clojure.contrib.duck-streams)
(import '(java.net Socket ServerSocket)
        '(java.io PrintWriter)
	'(java.io File FileInputStream RandomAccessFile))

(def *port* 3003)
(def s "115")
(def p "112")
(def n "110")
(def dB "db-1x2.db")

(defn accion-de-agente
	"Decides what to do with the request that arrives,
	it can be to send the database, or update it."
  [_ socket]
  (with-open [input (.getInputStream socket)
  	  output (.getOutputStream socket)
  	  readfile (FileInputStream. (File. dB))
  	  fileserver (RandomAccessFile. dB "rw")]
  	  (let [c (.read input)]
  	  	  (when (not= c -1)
  	  	  	  (if (.equals p (.toString c))	
  	  	  	  	  (let [buff (byte-array 1024)]
  	  	  	  	  	(loop [reed (.read readfile buff)]
  	  	  	  	  		(if (> reed 0)
							(do
								(.write output buff, 0, reed)
			  					(recur (.read readfile buff)))))))
  	  	  	  (if (.equals s (.toString c))
  	  	  	  	  (let [buff (byte-array 1024)]
  	  	  	  	  	  (loop [reed (.read readfile buff)]
  	  	  	  	  	  	  (if (> reed 0)
  	  	  	  	  	  	  	  (do
  	  	  	  	  	  	  	  	  (.write output buff, 0, reed)
			  					  (recur (.read readfile buff)))))))
			  (if (.equals n (.toString c))
			  	  (do
			  	  	  (.read input)
			  	  	  (.read input)
			  	  	  (loop []
						(let [c (.read input)]
						  (when (not= c -1)
							  (.write fileserver c)
				  			(recur)))))
			  )
			  (.flush output)
))))
				
(defn sirve
	"Starts the server and waits for connections"
  []  
  (let [servidor       (ServerSocket. *port*)
        agente         (agent nil)]
    (loop []
      (println "Esperando conexion...")      
      (let [socket (.accept servidor)]  
        (send-off agente accion-de-agente socket))        
      (recur))))


